<?php

/**
 * SmartPHP framework
 *
 * @name SmartPHP framework
 * @package SmartPHP
 * @author 费尔 <admin@smartphp.cn>
 * @version 1.0 Beta
 * @link http://www.smartphp.cn
 * @copyright smartphp.cn
 * @license <a href="http://www.smartphp.cn">smartphp</a>
 */

namespace Base;

/**
 * 缓存类
 * @author 费尔 <admin@smartphp.cn>
 */
class Cache {

    static $driver;

    public function __construct($driver = NULL, $options = []) {
        return self::init($driver, $options);
    }

    public static function init($driver = NULL, $options = []) {
        static $_cache;
        $class = '\\Driver\\Cache\\' . ucfirst(strtolower($driver ?: Config::get('cache.type')));
        return $_cache[$driver] ?? ($_cache[$driver] = new $class($options));
    }

    /**
     * 读取缓存
     *
     * @access public
     * @param string $name 缓存变量名
     * @return mixed
     */
    public static function get($name) {
        return self::init()->get($name);
    }

    /**
     * 写入缓存
     *
     * @access public
     * @param string $name 缓存变量名
     * @param mixed $value 存储数据
     * @param int $expire 有效时间 0为永久
     * @return boolean
     */
    public static function set($name, $value, $expire = null) {
        return self::init()->set($name, $value, $expire);
    }

    /**
     * 删除缓存
     *
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public static function rm($name) {
        return self::init()->rm($name);
    }

    /**
     * 清除缓存
     *
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public static function clear() {
        return self::init()->clear();
    }

    /**
     * 快速文件数据读取和保存 针对简单类型数据 字符串、数组
     * @access public
     * @param string $name 缓存名称
     * @param mixed $value 缓存值
     * @param string $path 缓存路径
     * @return mixed
     */
    public static function file($name, $value = '', $path = TEMP_PATH) {
        static $_cache = [];
        $filename = rtrim($path, '\\/') . DS . md5($name) . '.php';
        if ('' !== $value) {
            if (is_null($value)) {
                unset($_cache[$name]);
                return File::delete($filename);
            } else {
                $_cache[$name] = $value;
                return File::write($filename, serialize($value));
            }
        }
        return $_cache[$name] ?? ($_cache[$name] = unserialize(File::read($filename)));
    }

}
